<?php
class Controller_Sales_Order extends Controller_Abstract
{
	function actionCreate()
	{
		$this->_view['title'] = '创建销售订单';
		$this->_view['user'] = User::getONdutyUser();
		$this->_view['shop'] = Shop_User_Mapping::getTreeShopByPlatform();
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		$this->_view['currency'] = Currency::find()->asArray()->getAll();
		$this->_view['shipping_method_data'] = json_encode(Shipping_Method::getTreeShippingMethod('shipping_method_id'));
		if (isset($_GET['id']) && $_GET['id'])
		{
			$sales_order = Sales_Order::find('id=?', $_GET['id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$this->_view['customer'] = Sales_Order_Customer_Info::find('sales_order_id=?', $_GET['id'])->asArray()->getOne();
				if (isset($_GET['type']) && $_GET['type'])
				{
					$sales_order['item'] = Sales_Order_Item::find('sales_order_id=?', $_GET['id'])
						->joinLeft('product_basic', 'product_basic.number as product_basic_number', 'product_basic.id=sales_order_item.product_basic_id')
						->asArray()->getAll();
					foreach ($sales_order['item'] as $k => $i)
					{
						$sales_order['item'][$k]['attr'] = Sales_Order_Item_Attribute::find('sales_order_item_id=?', $i['id'])->asArray()->getAll();	
					}
				}			
				$this->_view['sales_order'] = $sales_order;
			}
			else
			{
				return $this->_redirectMessage('操作失败', $mapping['message'], $_SERVER['HTTP_REFERER'], $mapping['ack']);
			}
		}
	}
	
	function actionCreateSave()
	{
		$this->_view['title'] = '创建销售订单（保存）';
		if ($this->_context->isPOST())
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == FAILURE)
			{
				return $this->_redirectMessage('创建失败', $mapping['message'], $_SERVER['HTTP_REFERER'], $mapping['ack']);
			}
			$shipping_method = Shipping_Method::find('id=?', $_POST['shipping_method_id'])->asArray()->getOne();
			if ( ! $shipping_method)
			{
				return $this->_redirectMessage('创建失败', '邮寄方式错误！', $_SERVER['HTTP_REFERER'], FAILURE);
			}
			$sales_order = array(
					'warehouse_id' => $shipping_method['warehouse_id'],
					'shop_id' => $_POST['shop_id'],
					'shop_order_number' => trim($_POST['shop_order_number']),
					'send_method' => $_POST['send_method'],
					'resend_reason' => trim($_POST['resend_reason']),
					'resend_sales_order_id' => $_POST['resend_sales_order_id'],
					'sales_user_id' => $_POST['sales_user_id'],
					'sales_time' => $_POST['sales_time'],
					'shipping_method' => $shipping_method['id'],
					'payment_method' => $_POST['payment_method'],
					'shipping_fee' => trim($_POST['shipping_fee']),
					'discount' => trim($_POST['discount']),
					'currency_id' => $_POST['currency_id'],
					'transaction_id' => trim($_POST['transaction_id']),
					'shop_buyer_id' => trim($_POST['shop_buyer_id']),
					'fullname' => trim($_POST['fullname']),
					'phone' => trim($_POST['phone']),
					'email' => trim($_POST['email']),
					'street1' => trim($_POST['street1']),
					'street2' => trim($_POST['street2']),
					'city' => trim($_POST['city']),
					'state' => trim($_POST['state']),
					'zip' => trim($_POST['zip']),
					'country' => trim($_POST['country']),
					'country_cn' => isset($_POST['country_cn']) ? $_POST['country_cn'] : '',
					'address_notes' => isset($_POST['address_notes']) ? $_POST['address_notes'] : '',
					'item' => isset($_POST['item']) ? $_POST['item'] : array()
			);
			$result = Sales_Order::create($sales_order);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('保存成功', '正在返回..', url('Sales::Order/List'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('保存失败', $result['message'], url('Sales::Order/Create'), $result['ack']);
			}
		}
	}
	
	function actionList()
	{
		$this->_view['title'] = '销售单列表';
		$this->_view['shop_group'] = Shop_User_Mapping::getTreeShopByPlatform();
		$warehouse = Warehouse::getActiveWarehouse();
		$this->_view['warehouse'] = $warehouse;
		$this->_view['shipping_method'] = Shipping_Method::getTreeShippingMethod();
		$this->_view['shipping_method_data'] = json_encode(Shipping_Method::getTreeShippingMethod('shipping_method_id'));
		if (isset($_GET['is_search']))
		{
			$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
			$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
			$condition = Helper_BSS_Normal::buildCondition();
			$condition['shop_user_mapping'] = Shop_User_Mapping::getShopIdByUserId();
			$condition['trash_status'] = Q::ini('custom_flag/sales_order_trash_status/normal/value');
			if (isset($condition['order_status'][Q::ini('custom_flag/sales_order_handle_status/new/value')]) && $condition['order_status'][Q::ini('custom_flag/sales_order_handle_status/new/value')] == Q::ini('custom_flag/sales_order_handle_status/new/value') && count($condition['order_status']) == 1)
			{
				$order = 'sales_order_customer_info.shop_buyer_id asc';
			}
			else
			{
				$order = 'unix_timestamp(sales_order.sales_time) asc';
			}
	 		$result = Sales_Order::search($condition, $cp, $ps, $order);
			if ($result['ack'] == SUCCESS)
			{
				$sales_order = $result['data'];
				$page = new Helper_BSS_Page($result['pagination'], url('Sales::Order/List', $condition));
				$this->_view['page'] = $page->getPage();
				Sales_Order_Notes::getOrderNotes($sales_order);
				Sales_Order_Item_Attribute::getSalesOrderItemAttr($sales_order);
				Sales_Order::checkWarning($sales_order);
				Sales_Order::checkBuyer($sales_order);
				Sales_Refund::getSalesRefund($sales_order);
				$this->_view['sales_order'] = $sales_order;
			}
		}
	}
	
	function actionExpressBY()
	{
		$this->_view['title'] = '同步贝易';
		$sales_order_ids = explode(',', $_POST['info']);
		$post_type = isset($_POST['post_type']) ? $_POST['post_type'] : 1;
		if ($sales_order_ids)
		{
			$result = Sales_Order::BYExpressSync($sales_order_ids, $_POST['order_type'], $post_type);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('同步成功', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('同步失败', $result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('没有符合条件订单', '请检查订单是否符合条件', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionExpressQT()
	{
		$this->_view['title'] = '同步全通EUB';
		$sales_order_ids = explode(',', $_POST['info']);
		if ($sales_order_ids)
		{
			$result = Sales_Order::QTExpressSync($sales_order_ids, '广州E邮宝');
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('同步成功', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('同步失败', $result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('没有符合条件订单', '请检查订单是否符合条件', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionAddNotes()
	{
		$this->_view['title'] = '添加销售备注';
		if ($this->_context->isPOST())
		{
			$sales_order = Sales_Order::find('id=?', $_POST['id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order_Notes::create($_POST['id'], $_POST['notes_content'], Q::ini('custom_flag/sales_order_notes_type/sales/value'));
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('添加成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('添加失败', '该订单不存在', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('添加失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
	}
	
	function actionAddOrderNotes()
	{
		$this->_view['title'] = '添加订单备注';
		if ($this->_context->isPOST())
		{
			$sales_order = Sales_Order::find('id=?', $_POST['id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order_Notes::create($_POST['id'], $_POST['notes_content'], Q::ini('custom_flag/sales_order_notes_type/order/value'));
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('添加成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('添加失败', '该订单不存在', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('添加失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
	}
	
	function actionMarkOrder()
	{
		$this->_view['title'] = '标识漏/错发订单信息';
		if($this->_context->isPOST())
		{		
			if($_POST['id'] && isset($_POST['markorder_reason']))
			{
				$result = Sales_Order::markorder($_POST['id'],$_POST['markorder_reason']);
				if($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('已标识漏/错发订单', '正在返回..', $_SERVER['HTTP_REFERER'],$result['ack']);
				}
				else
				{
					return $this->_redirectMessage('操作失败', $result['message'], $_SERVER['HTTP_REFERER'],$result['ack']);
				}
			}
			else 
			{
				return $this->_redirectMessage('操作失败', '请选择错漏发原因！', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	} 
	
	function actionTrash()
	{
		$this->_view['title'] = '转为废弃单';
		if ($this->_context->isPOST())
		{
			$ids = explode(',', $_POST['id']);
			if ($ids)
			{
				$sales_order = Sales_Order::find('id in (?)', $ids)->asArray()->getAll();
				$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
				$mapping = Shop_User_Mapping::checkMapping($shop_id);
				if ($mapping['ack'] == SUCCESS)
				{
					$result = Sales_Order::trash($ids, trim($_POST['trash_reason']));
					if ($result['ack'] == SUCCESS)
					{
						return $this->_redirectMessage('已转为废弃单', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
					}
					else
					{
						return $this->_redirectMessage('操作失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
					}
				}
				else
				{
					return $this->_redirectMessage('操作失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('操作失败', '没有选中销售订单', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}
	
	function actionCombine()
	{
		$this->_view['title'] = '合并销售订单';
		$number = explode("\n", $_POST['number']);
		foreach ($number as &$val)
		{
			$val = trim($val);
		}
		unset($val);
		$sales_order = Sales_Order::find('id=? or number in (?)', $_POST['id'], $number)->asArray()->getAll();
		$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
		$mapping = Shop_User_Mapping::checkMapping($shop_id);
		if ($mapping['ack'] == SUCCESS)
		{
			$result = Sales_Order::combine($_POST['id'], $number);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('合并成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('合并失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('合并失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
		}
	}
	
	function actionTrashList()
	{
		$this->_view['title'] = '废弃单列表';
		$this->_view['shop'] = Shop_User_Mapping::getTreeShopByPlatform();
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['shop_user_mapping'] = Shop_User_Mapping::getShopIdByUserId();
		$condition['trash_status'] = Q::ini('custom_flag/sales_order_trash_status/trashed/value');
		$result = Sales_Order::search($condition, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$sales_order = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Sales::Order/TrashList', $condition));
			$this->_view['page'] = $page->getPage();
			Sales_Order_Notes::getOrderNotes($sales_order);
			Sales_Order_Item_Attribute::getSalesOrderItemAttr($sales_order);
			$this->_view['sales_order'] = $sales_order;
		}
	}
	
	function actionTrashReturn()
	{
		$this->_view['title'] = '废弃单恢复';
		$sales_order = Sales_Order::find('id=?', $_GET['id'])->asArray()->getOne();
		$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
		if ($mapping['ack'] == SUCCESS)
		{
			$result = Sales_Order::trashReturn($_GET['id']);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('已成功恢复', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('恢复失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('恢复失败', $mapping['message'], url('Sales::Order/TrashList'), $mapping['ack']);
		}
	}
	
	function actionDelete()
	{
		$this->_view['title'] = '彻底删除订单';
		$ids = explode(',', $_GET['id']);
		if ($ids)
		{
			$sales_order = Sales_Order::find('id in (?)', $ids)->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::delete($ids);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('删除成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('删除失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('删除失败', $mapping['message'], url('Sales::Order/TrashList'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('删除失败', '没有选中废弃订单', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionOrderInfoEdit()
	{
		$this->_view['title'] = '编辑订单';
		$id = isset($_GET['id']) ? $_GET['id'] : 0;
		if ($id)
		{
			$sales_order = Sales_Order::find('sales_order.id=?', $id)
				->joinLeft('shop', 'name as shop_name', 'shop.id=sales_order.shop_id')
				->joinLeft('currency', 'symbol as currency_symbol', 'currency.id=sales_order.currency_id')
				->joinLeft('warehouse', 'warehouse.code as warehouse_code', 'warehouse.id=sales_order.warehouse_id')
				->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$this->_view['shipping_method'] = Shipping_Method::getActiveShippingMethod();
				$resend_order = Sales_Order::find('id=?', $sales_order['resend_sales_order_id'])->asArray()->getOne();
				$sales_order['resend_sales_order_id'] = $resend_order['number'];
				$this->_view['currency'] = Currency::find()->asArray()->getAll();
				$this->_view['customer'] = Sales_Order_Customer_Info::find('sales_order_id=?', $_GET['id'])->asArray()->getOne();
				$this->_view['sales_order'] = $sales_order;
			}
			else
			{
				return $this->_redirectMessage('错误', $mapping['message'], url('sales::Order/List'), $mapping['ack']);
			}
		}
		else	
		{
			return $this->_redirectMessage('错误', '没有指定订单', url('Sales::Order/List'), FAILURE);
		}
	}
	
	function actionOrderInfoEditSave()
	{
		$this->_view['title'] = '编辑订单（保存）';
		if ($this->_context->isPOST())
		{
			$sales_order = Sales_Order::find('id=?', $_POST['id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::editOrderInfo($_POST);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('保存成功', '正在返回..', $_POST['history'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('保存失败', $result['message'], $_POST['history'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('保存失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
	}
	
	function actionProductInfoEdit()
	{
		$this->_view['title'] = '修改产品信息';
		$id = isset($_GET['id']) ? $_GET['id'] : 0;
		if ($id)
		{
			$sales_order = Sales_Order::find('sales_order.id=?', $id)
				->joinLeft('shop', 'name as shop_name', 'shop.id=sales_order.shop_id')
				->joinLeft('currency', 'symbol as currency_symbol', 'currency.id=sales_order.currency_id')
				->joinLeft('shipping_method', 'name as shipping_method_name', 'shipping_method.id=sales_order.shipping_method')
				->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$resend_order = Sales_Order::find('id=?', $sales_order['resend_sales_order_id'])->asArray()->getOne();
				$sales_order['resend_sales_order_id'] = $resend_order['number'];
				$sales_order = array($sales_order);
				Sales_Order_Item_Attribute::getSalesOrderItemAttr($sales_order);
				$sales_order = $sales_order[0];
				$this->_view['sales_order'] = $sales_order;
				$this->_view['customer'] = Sales_Order_Customer_Info::find('sales_order_id=?', $_GET['id'])->asArray()->getOne();
				$this->_view['shipping_method_data'] = json_encode(Shipping_Method::getTreeShippingMethod('shipping_method_id'));
			}
			else
			{
				return $this->_redirectMessage('错误', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('错误', '没有指定订单', url('Sales::Order/List'), FAILURE);
		}
	}
	
	function actionProductInfoEditSave()
	{
		$this->_view['title'] = '修改产品信息（保存）';
		if ($this->_context->isPOST())
		{
			$sales_order = Sales_Order::find('id=?', $_POST['sales_order_id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == FAILURE)
			{
				return $this->_redirectMessage('创建失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
			$shipping_method = Shipping_Method::find('id=?', $_POST['shipping_method_id'])->asArray()->getOne();
			if (! $shipping_method)
			{
				return $this->_redirectMessage('创建失败', '邮寄方式错误！', $_SERVER['HTTP_REFERER'], FAILURE);
			}
			$sales_order_id = $_POST['sales_order_id'];
			$item = array();
			$item = array();
			$key_arr = array();
			foreach ($_POST as $key => $value)
			{
				if (substr($key,0,15) == 'product_number_')
				{
					$key_arr[] = substr($key,15,strlen($key)-15);
				}
				$temp_arr = explode('_', $key);
				if ($temp_arr[0] == 'order' && $temp_arr[1] == 'item')
				{
					if ( ! array_key_exists($temp_arr[2], $item))
					{
						$item[$temp_arr[2]] = array();
					}
					if ($temp_arr[3] == 'attr')
					{
						$item[$temp_arr[2]]['attr'][$temp_arr[4]][$temp_arr[5]] = $value;
					}
					else
					{
						$item[$temp_arr[2]][$temp_arr[3]] = $value;
					}
				}
			}
			foreach ($key_arr as $k)
			{
				$temp = array();
				$temp['product_basic_number'] = trim($_POST['product_number_'.$k]);
				$temp['sales_price'] = trim($_POST['sales_price_'.$k]);
				$temp['quantity'] = trim($_POST['quantity_'.$k]);
				$temp['shop_item_id'] = trim($_POST['shop_item_id_'.$k]);
				$temp['shop_transaction_id'] = trim($_POST['shop_transaction_id_'.$k]);
				$temp['gift_flag'] = isset($_POST['gift_flag_'.$k]) ? $_POST['gift_flag_'.$k] : 0;
				$item_arr[$k] = $temp;
				$item_arr[$k]['attr'] = isset($item[$k]['attr']) ? $item[$k]['attr'] : array();
			}
			$order = array(
				'id' => $_POST['sales_order_id'],
				'shipping_method' => $shipping_method['id'],
				'warehouse_id' => $shipping_method['warehouse_id'],
				'item' => $item_arr
			);
			$result = Sales_Order::editProductInfo($order);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('修改完成', '返回列表', $_POST['history'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('修改失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionCheckOut()
	{
		$this->_view['title'] = '确认订单ajax';
		$sales_order_ids = explode(',', $_REQUEST['id']);
		if ($sales_order_ids)
		{
			$sales_order = Sales_Order::find('id in (?)', $sales_order_ids)->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::changeHandleStatusFromNewOrSalesHoldToCheckout($sales_order_ids);
				if ($result['ack'] == SUCCESS)
				{
					echo "确认成功";exit;
				}
				else
				{
					echo $result['message'];exit;
				}
			}
			else
			{
				echo $mapping['message'];exit;
			}
		}
	}
	
	function actionMultiCheckOut()
	{
		if ($this->_context->isPOST())
		{
			$sales_order_ids = explode(',', $_POST['info']);
			$sales_order = Sales_Order::find('id in (?)', $sales_order_ids)->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::changeHandleStatusFromNewOrSalesHoldToCheckout($sales_order_ids);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('确认成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('部分确认失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('操作失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
	}
	
	function actionSalesHold()
	{
		$this->_view['title'] = '滞留订单ajax';
		$sales_order_ids = explode(',', $_REQUEST['id']);
		if ($sales_order_ids)
		{
			$sales_order = Sales_Order::find('id in (?)', $sales_order_ids)->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::changeHandleStatusFromNewOrCheckoutToSalesHold($sales_order_ids);
				if ($result['ack'] == SUCCESS)
				{
					echo "滞留成功";exit;
				}
				else
				{
					echo $result['message'];exit;
				}
			}
			else
			{
				echo $mapping['message'];exit;
			}
		}
	}
	
	function actionMultiSalesHold()
	{
		if ($this->_context->isPOST())
		{
			$sales_order_ids = explode(',', $_POST['info']);
			$sales_order = Sales_Order::find('id in (?)', $sales_order_ids)->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::changeHandleStatusFromNewOrCheckoutToSalesHold($sales_order_ids);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('滞留成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('部分滞留失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('操作失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
	}
	
	function actionWantedEdit()
	{
		$this->_view['title'] = '标识需要改的订单';
		$sales_order = Sales_Order::find('id=?', $_GET['id'])->asArray()->getOne();
		$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
		if ($mapping['ack'] == SUCCESS)
		{
			if ($sales_order['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/assigned/value') or $sales_order['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/printed/value') or $sales_order['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/printed_address/value') or $sales_order['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/weighed/value') or $sales_order['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/warehouse_hold/value'))
			{
				QDB::getConn()->execute('update sales_order set tips_flag=1 where id=' . $_GET['id']);
				return $this->_redirectMessage('标识成功', '正在返回..', $_SERVER['HTTP_REFERER'], $mapping['ack']);
			}
			else
			{
				return $this->_redirect($_SERVER['HTTP_REFERER']);
			}
		}
		else
		{
			return $this->_redirectMessage('标识失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
		}
	}
	
	function actionPostEUBpackage()
	{
		$this->_view['title'] = '同步E邮宝';
		$id = $_REQUEST['id'];
		if ($id)
		{
			$sales_order = Sales_Order::find('id=?', $id)->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$add_result = Sales_Order::EUBPostPackage($id);
				if ($add_result['ack'] == SUCCESS)
				{
					echo json_encode(array('ack'=> 'success', 'message'=>'同步成功'));exit;
				}
				else
				{
					echo json_encode(array('ack' => 'failure', 'message' => $add_result['message']));exit;
				}
			}
			else
			{
				echo json_encode(array('ack' => 'failure', 'message' => $mapping['message']));exit;
			}
		}
	}
	
	function actionRemovedEUBpackage()
	{
		$this->_view['title'] = '清空E邮宝';
		$id = $_REQUEST['id'];
		if ($id)
		{
			$sales_order = Sales_Order::find('id=?', $id)->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$repost_result = Sales_Order::EUBRemovedPackage($id);
				if ($repost_result['ack'] == SUCCESS)
				{
					echo json_encode(array('ack'=> 'success', 'message'=>'清除成功'));exit;
				}
				else
				{
					echo json_encode(array('ack' => 'failure', 'message' => $repost_result['message']));exit;
				}
			}
			else
			{
				echo json_encode(array('ack' => 'failure', 'message' => $mapping['message']));exit;
			}
		}
	}
	
	function actionPostIEUBPackage()
	{
		$this->_view['title'] = '同步国际EUB';
		$id = $_REQUEST['id'];
		$sales_order = Sales_Order::find('id=?', $id)->asArray()->getOne();
		$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
		if ($mapping['ack'] == SUCCESS)
		{
			$result = Sales_Order::IEUBPostPackage($id);
			if ($result['ack'] == SUCCESS)
			{
				echo json_encode(array('ack' => 'success', 'message' => '同步成功'));
			}
			else
			{
				echo json_encode(array('ack' => 'failure', 'message' => $result['message']));
			}
			exit;
		}
		else
		{
			echo json_encode(array('ack' => 'failure', 'message' => $mapping['message']));exit;
		}
	}
	
	function actionRemovedIEUBPackage()
	{
		$this->_view['title'] = '清除国际EUB';
		$sales_order = Sales_Order::find('id=?', $_REQUEST['id'])->asArray()->getOne();
		$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
		if ($mapping['ack'] == SUCCESS)
		{
			Sales_Order::IEUBRemovedPackage($_REQUEST['id']);
			echo json_encode(array('ack' => 'success', 'message' => ''));exit;
		}
		else
		{
			echo json_encode(array('ack' => 'failure', 'message' => $mapping['message']));exit;
		}
	}
	
	function actionImport()
	{
		$this->_view['title'] = '导入订单';
		$wish_shop = Shop_User_Mapping::getShopByPlatform('wish');
		$this->_view['wish_shop'] = $wish_shop;
		$ebay_shop = Shop_User_Mapping::getShopByPlatform('ebay');
		$this->_view['ebay_shop'] = $ebay_shop;
		$zencart_shop = Shop_User_Mapping::getShopByPlatform('zencart');
		$this->_view['zencart_shop'] = $zencart_shop;
		$magento_shop = Shop_User_Mapping::getShopByPlatform('magento');
		$this->_view['magento_shop'] = $magento_shop;
		$amazon1 = Shop_User_Mapping::getShopByPlatform('IAINSWAN');
		$amazon2 = Shop_User_Mapping::getShopByPlatform('DAVIDSONNE');
		$amazon3 = Shop_User_Mapping::getShopByPlatform('Orr');
		$amazon4 = Shop_User_Mapping::getShopByPlatform('robertaspland');
		$amazon5 = Shop_User_Mapping::getShopByPlatform('NNJYCE');
		$amazon6 = Shop_User_Mapping::getShopByPlatform('shariwilliams');
		$amazon7 = Shop_User_Mapping::getShopByPlatform('TODD');
		$this->_view['amazon_shop'] = array_merge($amazon1, $amazon2, $amazon3, $amazon4, $amazon5, $amazon6, $amazon7);
		$aliexpress_shop = Shop_User_Mapping::getShopByPlatform('aliexpress');
		$this->_view['aliexpress_shop'] = $aliexpress_shop;
		$newegg_shop = Shop_User_Mapping::getShopByPlatform('neweggs');
		$this->_view['newegg_shop'] = $newegg_shop;
	}
	
	function actionImportAmazonOrderByAPI()
	{
		set_time_limit(0);
		$this->_view['title'] = '导入amazon订单（API）';
		if ($_POST['shop_id'] && $_POST['begin_sales_time'])
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$amazon_shop = Shop_API_Amazon::find('shop_id=?', $_POST['shop_id'])
					->joinLeft('shop', '', 'shop.id=shop_api_amazon.shop_id')
					->asArray()->getOne();
				$result = Helper_BSS_API::AutoImportAmazonOrder(array($amazon_shop), $_POST['begin_sales_time'], $_POST['end_sales_time']);
				if ($result['ack'] == SUCCESS && $result['message'] == '')
				{
					return $this->_redirectMessage('导入成功', '返回销售单浏览页面', url('Sales::Order/List', array('shop_id' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('导入部分失败', $result['message'], url('Sales::Order/List', array('shop_id' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('导入失败', '请选择店铺/日期！', url('Sales::Order/Import'), FAILURE);
		}
	}
	
	function actionImportAmazonOrderByXlsx()
	{
		$this->_view['title'] = '导入amazon订单（XLSX）';
		if (isset($_POST['shop_id']) && $_POST['shop_id'])
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$upload_result = Upload_Files::uploadFile('sales_order', Q::ini('custom_flag/upload_file_type/sales_order/value'));
				if ($upload_result['ack'] == SUCCESS)
				{
					$filename = $upload_result['path'];
					$sales_order_in_xlsx = Helper_BSS_CSV::importAmazonOrderByXlsx($filename);
					$result = array();
					$shop = Shop::find('id=?', $_POST['shop_id'])->asArray()->getOne();
					$currency = Currency::find('id=?', ($shop['name'] == 'yes_amz_us') ? 2 : (($shop['name'] == 'yes_amz_uk') ? 3 : 6))->asArray()->getOne();
					foreach ($sales_order_in_xlsx as $s)
					{
						$country = Country::find('code=?', trim($s[23]))->asArray()->getOne();
						$country_name_en = $country ? $country['en_name'] : trim($s[23]);
						$country_name_cn = $country ? $country['cn_name'] : '';
						$result[$s[0]]['param']['channel'] = 'MFN';
						$result[$s[0]]['shop_id'] = $_POST['shop_id'];
						$result[$s[0]]['shop_order_number'] = $s[0];
						$result[$s[0]]['sales_time'] = date('Y-m-d H:i:s', strtotime($s[2]));
						$result[$s[0]]['paid_time'] = date('Y-m-d H:i:s', strtotime($s[3]));
						$result[$s[0]]['shipping_method'] = Shipping_Method::getShippingMethodByCode('GZ_R_SG_Package');
						$result[$s[0]]['payment_method'] = Q::ini('custom_flag/sales_order_payment_method/amazon/value');
						$result[$s[0]]['shipping_fee'] = $s[13];
						$result[$s[0]]['discount'] = 0;
						$result[$s[0]]['amount'] = 0;
						$result[$s[0]]['currency_id'] = 1;
						$result[$s[0]]['currency_rate'] = '1.0000';
						$result[$s[0]]['transaction_id'] = $s[0];
						$result[$s[0]]['shop_buyer_id'] = $s[5];
						$result[$s[0]]['fullname'] = $s[5];
						$result[$s[0]]['email'] = $s[4];
						$result[$s[0]]['phone'] = $s[6];
						$result[$s[0]]['street1'] = $s[17];
						$result[$s[0]]['street2'] = $s[18];
						$result[$s[0]]['city'] = $s[20];
						$result[$s[0]]['state'] = $s[21];
						$result[$s[0]]['zip'] = $s[22];
						$result[$s[0]]['country'] = $country_name_en;
						$result[$s[0]]['country_cn'] = $country_name_cn;
						$item = array();
						$item_number = explode('-', $s[7]);
						if (count($item_number) >= 2)
						{
							$number = explode('X', $item_number[0]);
							$item['product_basic_number'] = $number[0];
							if (count($number) == 2)
							{
								$item['quantity'] = $s[9]*$number[1];
							}
							else
							{
								$item['quantity'] = $s[9];
							}
						}
						else
						{
							$item['product_basic_number'] = $s[7];
							$item['quantity'] = $s[9];
						}
						$item['shop_item_id'] = $s[1];
						$item['sales_price'] = $s[11]/$item['quantity'];
						$result[$s[0]]['item'][] = $item;
					}
					foreach ($result as $k => $r)
					{
						foreach($r['item'] as $ri) 
						{
							$result[$k]['amount'] += $ri['sales_price']*$ri['quantity'];
						}
					}
					$sales_order_result = Sales_Order::import($result);
					if ($sales_order_result['ack'] == SUCCESS)
					{
						return $this->_redirectMessage('导入成功', '返回销售单浏览页面', url('Sales::Order/List', array('shop_id'=>$_POST['shop_id'], 'order_status'=>array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
					}
					else
					{
						return $this->_redirectMessage('导入部分失败', $sales_order_result['message'], url('Sales::Order/List', array('shop_id'=>$_POST['shop_id'], 'order_status'=>array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
					}
				}
				else
				{
					return $this->_redirectMessage('上传文件失败', $upload_result['message'], $_SERVER['HTTP_REFERER'], $upload_result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('导入失败', '请选择店铺', url('Sales::Order/Import'), FAILURE);
		}
	}
	
	function actionImportEabyOrderByCsv()
	{
		$this->_view['title'] = '导入ebay订单（CSV）';
		if ($this->_context->isPOST())
		{
			if ($_POST['shop_id'] && isset($_POST['shop_id']))
			{
				$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
				if ($mapping['ack'] == SUCCESS)
				{
					$upload_result = Upload_Files::uploadFile('sales_order', Q::ini('custom_flag/upload_file_type/sales_order/value'));
					if ($upload_result['ack'] == SUCCESS)
					{
						$filename = $upload_result['path'];
						$sales_order_in_csv = Helper_BSS_CSV::importEabyOrderByCsv($filename);
						$result = array();
						foreach ($sales_order_in_csv as $s)
						{
							if (! array_key_exists($s['Sales Record Number'], $result))
							{
								$country = Country::find('en_name=?', trim($s['Buyer Country']))->asArray()->getOne();
								$country_name_en = $country ? $country['en_name'] : trim($s['Buyer Country']);
								$country_name_cn = $country ? $country['cn_name'] : '';
								$result[$s['Sales Record Number']]['shop_id'] = $_POST['shop_id'];
								$result[$s['Sales Record Number']]['shop_order_number'] = $s['Sales Record Number'];
								$result[$s['Sales Record Number']]['shop_buyer_id'] = $s['User Id'];
								$result[$s['Sales Record Number']]['fullname'] = $s['Buyer Fullname'];
								$result[$s['Sales Record Number']]['phone'] = $s['Buyer Phone Number'];
								$result[$s['Sales Record Number']]['email'] = $s['Buyer Email'];
								$result[$s['Sales Record Number']]['street1'] = $s['Buyer Address 1'];
								$result[$s['Sales Record Number']]['street2'] = $s['Buyer Address 2'];
								$result[$s['Sales Record Number']]['city'] = $s['Buyer City'];
								$result[$s['Sales Record Number']]['state'] = $s['Buyer State'] ? $s['Buyer State'] : $s['Buyer City'];
								$result[$s['Sales Record Number']]['zip'] = $s['Buyer Postcode'];
								$result[$s['Sales Record Number']]['country'] = $country_name_en;
								$result[$s['Sales Record Number']]['country_cn'] = $country_name_cn;
								$result[$s['Sales Record Number']]['shipping_fee'] = $s['Postage and Handling(origin)'];
								$result[$s['Sales Record Number']]['shipping_method'] = ($s['Buyer Country']=='United States') ? Shipping_Method::getShippingMethodByCode('GZ_N_EUB') : Shipping_Method::getShippingMethodByCode('GZ_N_HK_Package');
								$result[$s['Sales Record Number']]['discount'] = 0;
								$result[$s['Sales Record Number']]['amount'] = $s['Total Price'];
								$result[$s['Sales Record Number']]['payment_method'] = Q::ini('custom_flag/sales_order_payment_method/paypal/value');
								$result[$s['Sales Record Number']]['sales_time'] = date('Y-m-d H:i:s', strtotime($s['Sale Date']));
								$result[$s['Sales Record Number']]['paid_time'] = date('Y-m-d H:i:s', strtotime($s['Paid on Date']));
								$result[$s['Sales Record Number']]['transaction_id'] = $s['PayPal Transaction ID'];
							}
							if ($s['Custom Label'])
							{
								$item = array();
								$item['shop_item_title'] = $s['Item Title'];
								$item['product_basic_number'] = $s['Custom Label'];
								$item['quantity'] = $s['Quantity'];
								$item['sales_price'] = $s['Sale Price'];
								$item['shop_item_id'] = $s['Item Number'];
								$item['shop_transaction_id'] = $s['Transaction ID'];
								$result[$s['Sales Record Number']]['item'][] = $item;
							}
						}
						$currency = Currency::find()->asArray()->getAll();
						foreach ($result as $kr => &$r)
						{
							if (isset($r['item']) && $r['item'])
							{
								$currency_id = 0;
								$currency_rate = 0;
								foreach ($currency as $c)
								{
									$len = strlen($c['match_char']);
									if (substr($r['amount'], 0, $len) == $c['match_char'])
									{
										$result[$kr]['amount'] = substr($r['amount'], $len);
										$result[$kr]['shipping_fee'] = substr($r['shipping_fee'], $len);
										foreach ($r['item'] as $kri => $ri)
										{
											$r['item'][$kri]['sales_price'] = substr($ri['sales_price'], $len);
											$r['item'][$kri]['product_basic_number'] = substr($ri['product_basic_number'], 0, 6);
										}
										$currency_id = $c['id'];
										$currency_rate = $c['rate'];
									}
								}
							}
							$r['currency_id'] = $currency_id;
							$r['currency_rate'] = $currency_rate;
						}
						$sales_order_result = Sales_Order::import($result);
						if ($sales_order_result['ack'] == SUCCESS)
						{
							return $this->_redirectMessage('导入成功', '返回销售单浏览页面', url('Sales::Order/List', array('shop_id'=>$_POST['shop_id'], 'order_status'=>array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
						}
						else
						{
							return $this->_redirectMessage('导入部分失败', $sales_order_result['message'], url('Sales::Order/List', array('shop_id'=>$_POST['shop_id'], 'order_status'=>array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
						}
					}
					else
					{
						return $this->_redirectMessage('上传文件失败', $upload_result['message'], $_SERVER['HTTP_REFERER'], $upload_result['ack']);
					}
				}
				else
				{
					return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('导入失败', '请选择店铺', url('Sales::Order/Import'), FAILURE);
			}
		}
	}
	
	function actionImportEbayOrderByAPI()
	{
		$this->_view['title'] = '导入ebay订单（API）';
		if ($this->_context->isPOST())
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$mod_time_from = date('c', strtotime($_POST['begin_sales_time']));
				$mod_time_to = date('c', strtotime(empty($_POST['end_sales_time']) ? CURRENT_DATETIME : ($_POST['end_sales_time'] . ' 23:59:59')));
				$result = Sales_Order::importEbayOrderByAPI($_POST['shop_id'], $mod_time_from, $mod_time_to);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('导入成功', '返回列表', url('Sales::Order/List', array('shop_id[]' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('导入部分失败', $result['message'], url('Sales::Order/List', array('shop_id[]' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $result['ack']);
				}
			}
		}
	}
	
	function actionImportAliExpressOrderByAPI()
	{
		$this->_view['title'] = '导入速卖通订单（API）';
		if ($this->_context->isPost())
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$api = Shop_API_AliExpress::getAPIByShopId($_POST['shop_id']);
				if ($api['ack'] == SUCCESS && $_POST['begin_sales_time'])
				{
					$begin_sales_time = date('m/d/Y', strtotime($_POST['begin_sales_time']));
					$end_sales_time = $_POST['end_sales_time'] ? date('m/d/Y', strtotime($_POST['end_sales_time'])) : date('m/d/Y');
					$page = 0;
					$page_size = 50;
					$total = 1;  //确保进入循环
					$order_uri = Q::ini('custom_api/aliexpress_uri') . 'api.findOrderListQuery/' . $api['key'];
					$order = array();
					$order_list = array();
					while ($page * $page_size < $total)
					{
						$param = array(
							'access_token' => $api['access_token'],
							'page' => ++$page,
							'pageSize' => $page_size,
							'createDateStart' => $begin_sales_time,
							'createDateEnd' => $end_sales_time,
							'orderStatus' => 'WAIT_SELLER_SEND_GOODS'
						);
						$result = Helper_BSS_API::AliExpressAPICall($order_uri, $param, false);
						if (array_key_exists('orderList', $result))
						{
							$total = $result['totalItem'];
							foreach ($result['orderList'] as $r)
							{
								$order_list[] = $r;
							}
						}
					}
					if ($order_list)
					{
						$order_info_uri = Q::ini('custom_api/aliexpress_uri') . 'api.findOrderById/' . $api['key'];
						foreach ($order_list as $o)
						{
							$order_id = (string)$o['orderId'];
							$order[$order_id]['shop_id'] = $_POST['shop_id'];
							$order[$order_id]['shop_order_number'] = $order_id;
							$order[$order_id]['amount'] = $o['payAmount']['amount'];
							$currency = Currency::find('code=?', $o['payAmount']['currencyCode'])->asArray()->getOne();
							$order[$order_id]['currency_id'] = $currency['id'];
							$order[$order_id]['currency_rate'] = $currency['rate'];
							$order[$order_id]['shipping_method'] = Shipping_Method::getShippingMethodByCode('GZ_N_HK_Package');
							$order[$order_id]['payment_method'] = Q::ini('custom_flag/sales_order_payment_method/aliexpress/value');
							$order[$order_id]['sales_time'] = Helper_BSS_Normal::AliExpressDateTransfer($o['gmtCreate']);
							$order[$order_id]['paid_time'] = Helper_BSS_Normal::AliExpressDateTransfer($o['gmtPayTime']);
							$param = array(
								'access_token' => $api['access_token'],
								'orderId' => $order_id
							);
							$result = Helper_BSS_API::AliExpressAPICall($order_info_uri, $param, false);
							$order[$order_id]['fullname'] = $result['receiptAddress']['contactPerson'];
							$order[$order_id]['shop_buyer_id'] = $result['buyerInfo']['firstName']. ' ' .$result['buyerInfo']['lastName'];						
							$order[$order_id]['email'] = $result['buyerInfo']['email'];
							if ($result['receiptAddress']['country'] == 'UK')
							{
								$result['receiptAddress']['country'] = 'GB';
							}
							$country = Country::find('code=?', $result['receiptAddress']['country'])->asArray()->getOne();
							$order[$order_id]['country'] = $country['en_name'];
							$order[$order_id]['country_cn'] = $country['cn_name'];
							$order[$order_id]['state'] = $result['receiptAddress']['province'];
							$order[$order_id]['city'] = $result['receiptAddress']['city'];
							$order[$order_id]['street1'] = $result['receiptAddress']['detailAddress'];
							$order[$order_id]['street2'] = isset($result['receiptAddress']['address2']) ? $result['receiptAddress']['address2'] : '';
							if (isset($result['receiptAddress']['phoneArea']) && isset($result['receiptAddress']['phoneNumber']))
							{
								$phone = $result['receiptAddress']['phoneArea'] . '-' . $result['receiptAddress']['phoneNumber'];
								$order[$order_id]['phone'] = $phone;						
							}
							else
							{
								$order[$order_id]['phone'] = isset($result['receiptAddress']['mobileNo']) ? $result['receiptAddress']['mobileNo'] : '';
							}
							$order[$order_id]['zip'] = $result['receiptAddress']['zip'];
							$order[$order_id]['transaction_id'] = '';
							$product = array();
							$order[$order_id]['shipping_fee'] = 0;
							$total_product_amount = 0;
							foreach ($o['productList'] as $key => $op)
							{
								$product[$key]['product_basic_number'] = $op['skuCode'];
								$product[$key]['quantity'] = $op['productCount'];
								$product[$key]['sales_price'] = $op['productUnitPrice']['amount'];
								$total_product_amount += $op['totalProductAmount']['amount'];
								$product[$key]['shop_item_id'] = $op['productId'];
							}
							$order[$order_id]['item'] = $product;
							$order[$order_id]['shipping_fee'] = $result['logisticsAmount']['amount'];
							$order[$order_id]['discount'] = $total_product_amount + $order[$order_id]['shipping_fee'] - $o['payAmount']['amount'];
						}
						$sales_order_result = Sales_Order::import($order);
						if ($sales_order_result['ack'] == SUCCESS)
						{
							return $this->_redirectMessage('导入成功', '返回销售单浏览页面', url('Sales::Order/List', array('shop_id[]' => $_POST['shop_id'], 'order_status'=>array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
						}
						else
						{
							return $this->_redirectMessage('导入部分失败', $sales_order_result['message'], url('Sales::Order/List', array('shop_id[]' => $_POST['shop_id'], 'order_status'=>array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
						}
					}
					else
					{
						return $this->_redirectMessage('没有可导入的订单', '请重新选择店铺/日期', url('Sales::Order/Import'), FAILURE);
					}
				}
			}
			else
			{
				return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
			}
		}
	}
	
	function actionImportZencartOrderByAPI()
	{
		$this->_view['title'] = '导入zencart订单（API）';
		if ($this->_context->isPOST())
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$data = Helper_BSS_API::getZencartOrderByAPI($_POST['shop_id'], $_POST['begin_sales_time'], $_POST['end_sales_time']);
				$url_arr = array(
					'shop_id' => $_POST['shop_id'],
					'begin_sales_time' => $_POST['begin_sales_time'],
					'end_sales_time' => $_POST['end_sales_time'],
					'is_search' => 1
				);
				if ( ! $data)
				{
					return $this->_redirectMessage('没有任何订单', '返回导入页面', url('Sales::Order/Import'), FAILURE);
				}
				Helper_BSS_Normal::discount($data);
				$result = array();
				foreach ($data as $d)
				{
					$website = Shop::find('name=?', $d['web'])->asArray()->getOne();
					$website_id = $website['id'];
					$country = Country::find('en_name=?', $d['shipping_country'])->asArray()->getOne();
					$country_name_cn = $country ? $country['cn_name'] : '';
					if (! array_key_exists($d['no'], $result))
					{
						$result[$d['no']]['shop_id'] =$website_id;
						$result[$d['no']]['shop_order_number'] = $d['no'];
						$result[$d['no']]['shop_buyer_id'] = '';
						$result[$d['no']]['fullname'] = $d['shipping_fullname'];
						$result[$d['no']]['phone'] = $d['phone'];
						$result[$d['no']]['email'] = $d['email'];
						$result[$d['no']]['street1'] = $d['shipping_address'];
						$result[$d['no']]['street2'] = '';
						$result[$d['no']]['city'] = $d['shipping_city'];;
						$result[$d['no']]['state'] = $d['shipping_state'];;
						$result[$d['no']]['zip'] = $d['shipping_zip'];
						$result[$d['no']]['country'] = $d['shipping_country'];
						$result[$d['no']]['country_cn'] = $country_name_cn;
						$result[$d['no']]['shipping_fee'] = $d['s_fee'];
						$result[$d['no']]['shipping_method'] = $d['s_method'];
						$result[$d['no']]['discount'] = $d['discount'];
						$result[$d['no']]['amount'] = $d['amount'];
						$result[$d['no']]['payment_method'] = $d['p_method'];
						$result[$d['no']]['sales_time'] = $d['sale_time'];
						$result[$d['no']]['paid_time'] = $d['pay_time'];
						$result[$d['no']]['transaction_id'] = $d['transaction'];
					}
					if ($d['item'])
					{
						$item = array();
						foreach ($d['item'] as $i)
						{
							$item['shop_item_title'] = $i['title'];
							$item['product_basic_number'] = $i['no'];
							$item['quantity'] = $i['quantity'];
							$item['sales_price'] = $i['price'];
							if (isset($i['attr']) && $i['attr'])
							{
								$item_attr = array();
								foreach ($i['attr'] as $a)
								{
									$item_attr['name'] = $a['name'];
									$item_attr['value'] = $a['value'];
									$item_attr['price'] = $a['price'];
									$item_attr['prefix'] = $a['prefix'];
									$item['attr'][] = $item_attr;
								}
							}
							$result[$d['no']]['item'][] = $item;
						}
					}
					$currency = Currency::find('code=?', $d['code'])->asArray()->getOne();
					if (! $currency)
					{
						return $this->_redirectMessage('币种不存在', '请联系运维组人员', url('Sales::Order/Import'), FAILURE);
					}
					$result[$d['no']]['currency_id'] = $currency['id'];
					if ($d['p_method'] == Q::ini('custom_flag/sales_order_payment_method/ips/value'))
					{
						$currency_rate = $d['rate'];
					}
					else
					{
						$result[$d['no']]['currency_rate'] = $currency['rate'];
					}
				}
				$sales_order_result = Sales_Order::import($result);
				return $this->_redirectMessage('导入成功', '正在返回..', url('Sales::Order/List', $url_arr), $sales_order_result['ack']);
			}
			else
			{
				return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
			}
		}
	}
	
	function actionImportMagentoOrderByAPI()
	{
		$this->_view['title'] = '导入magento订单（API）';
		if ($this->_context->isPOST())
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$data = Helper_BSS_API::getMagentoOrderByAPI($_POST['shop_id'], $_POST['begin_sales_time'], $_POST['end_sales_time']);
				$url_arr = array(
					'shop_id' => $_POST['shop_id'],
					'begin_sales_time' => $_POST['begin_sales_time'],
					'end_sales_time' => $_POST['end_sales_time'],
					'is_search' => 1
				);
				if ( ! $data)
				{
					return $this->_redirectMessage('没有任何订单', '返回导入页面', url('Sales::Order/Import'), FAILURE);
				}
				Helper_BSS_Normal::discount($data);
				$result = array();
				foreach ($data as $d)
				{
					$website = Shop::find('name=?', $d['web'])->asArray()->getOne();
					$website_id = $website['id'];
					$country = Country::find('en_name=?', $d['shipping_country'])->asArray()->getOne();
					$country_name_cn = $country ? $country['cn_name'] : '';
					if (! array_key_exists($d['no'], $result))
					{
						$result[$d['no']]['shop_id'] =$website_id;
						$result[$d['no']]['shop_order_number'] = $d['no'];
						$result[$d['no']]['shop_buyer_id'] = '';
						$result[$d['no']]['fullname'] = $d['shipping_fullname'];
						$result[$d['no']]['phone'] = $d['phone'];
						$result[$d['no']]['email'] = $d['email'];
						$result[$d['no']]['street1'] = $d['shipping_address'];
						$result[$d['no']]['street2'] = '';
						$result[$d['no']]['city'] = $d['shipping_city'];;
						$result[$d['no']]['state'] = $d['shipping_state'];;
						$result[$d['no']]['zip'] = $d['shipping_zip'];
						$result[$d['no']]['country'] = $d['shipping_country'];
						$result[$d['no']]['country_cn'] = $country_name_cn;
						$result[$d['no']]['shipping_fee'] = $d['s_fee'];
						$result[$d['no']]['shipping_method'] = $d['s_method'];
						$result[$d['no']]['discount'] = $d['discount'];
						$result[$d['no']]['amount'] = $d['amount'];
						$result[$d['no']]['payment_method'] = $d['p_method'];
						$result[$d['no']]['sales_time'] = $d['sale_time'];
						$result[$d['no']]['paid_time'] = $d['pay_time'];
						$result[$d['no']]['transaction_id'] = $d['transaction'];
					}
					if ($d['item'])
					{
						$item = array();
						foreach ($d['item'] as $i)
						{
							$item['shop_item_title'] = $i['title'];
							$item['product_basic_number'] = $i['no'];
							$item['quantity'] = $i['quantity'];
							$item['sales_price'] = $i['price'];
							if (isset($i['attr']) && $i['attr'])
							{
								$item_attr = array();
								foreach ($i['attr'] as $a)
								{
									$item_attr['name'] = $a['name'];
									$item_attr['value'] = $a['value'];
									$item_attr['price'] = $a['price'];
									$item_attr['prefix'] = $a['prefix'];
									$item['attr'][] = $item_attr;
								}
							}
							$result[$d['no']]['item'][] = $item;
						}
					}
					$currency = Currency::find('code=?', $d['code'])->asArray()->getOne();
					if (! $currency)
					{
						return $this->_redirectMessage('币种不存在', '请联系运维组人员', url('Sales::Order/Import'), FAILURE);
					}
					$result[$d['no']]['currency_id'] = $currency['id'];
					if ($d['p_method'] == Q::ini('custom_flag/sales_order_payment_method/ips/value'))
					{
						$currency_rate = $d['rate'];
					}
					else
					{
						$result[$d['no']]['currency_rate'] = $currency['rate'];
					}
				}
				$sales_order_result = Sales_Order::import($result);
				return $this->_redirectMessage('导入成功', '正在返回..', url('Sales::Order/List', $url_arr), $sales_order_result['ack']);
			}
			else
			{
				return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
			}
		}
	}
	
	function actionImportNewEggOrderByXls()
	{
		$this->_view['title'] = '导入NewEgg订单（XLS）';
		if(isset($_POST['shop_id']) && ! empty($_POST['shop_id']))
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if($mapping['ack'] == SUCCESS)
			{
				$upload_result = Upload_Files::uploadFile('sales_order', Q::ini('custom_flag/upload_file_type/sales_order/value'));
				if($upload_result['ack'] == SUCCESS)
				{
					$sales_order_in_xls = Helper_BSS_XLS::importNewEggOrderByXls($upload_result['path']);
					$result = array();
					foreach($sales_order_in_xls as $s)
					{
						if( ! array_key_exists($s[2], $result))
						{
							if(!empty($s[14]))
							{
								$country = Country::find('code=?', trim($s[14]))->asArray()->getOne();
							}
							$country_name_en = $country ? $country['en_name'] : trim($s[14]);
							$country_name_cn = $country ? $country['cn_name'] : '';
							$currency = Currency::find('code=?', 'USD')->asArray()->getOne();
							$result[$s[2]]['shop_id'] = $_POST['shop_id'];
							$result[$s[2]]['shop_order_number'] = $s[2];
							$result[$s[2]]['sales_time'] = date('Y-m-d H:i:s', strtotime($s[3]));
							$result[$s[2]]['paid_time'] = date('Y-m-d H:i:s', strtotime($s[3]));
							$result[$s[2]]['shipping_method'] = Shipping_Method::getShippingMethodByCode('GZ_N_EUB');
							$result[$s[2]]['payment_method'] = Q::ini('custom_flag/sales_order_payment_method/newegg/value');
							$result[$s[2]]['shipping_fee'] = $s[7];
							$result[$s[2]]['currency_id'] = $currency['id'];
							$result[$s[2]]['currency_rate'] = $currency['rate'];
							$result[$s[2]]['transaction_id'] = '';
							$result[$s[2]]['fullname'] = $s[15];
							$result[$s[2]]['email'] = $s[18];
							$result[$s[2]]['phone'] = $s[17];
							$result[$s[2]]['street1'] = $s[9];
							$result[$s[2]]['street2'] = $s[10];
							$result[$s[2]]['city'] = $s[11];
							$result[$s[2]]['state'] = $s[12];
							$result[$s[2]]['zip'] = $s[13];
							$result[$s[2]]['country'] = $country_name_en;
							$result[$s[2]]['country_cn'] = $country_name_cn;
							$result[$s[2]]['amount'] = $s[8];
							$result[$s[2]]['discount'] = $result[$s[2]]['shipping_fee'] - $result[$s[2]]['amount'];
						}
						$item = array();
						$item['product_basic_number'] = $s[20];
						$item['shop_item_id'] = $s[21];
						$item['quantity'] = $s[24];
						$item['sales_price'] = $s[22];
						$result[$s[2]]['item'][] = $item;
						$result[$s[2]]['discount'] += $item['quantity'] * $item['sales_price'];
					}
					$sales_order_result = Sales_Order::import($result);
					if($sales_order_result['ack'] == SUCCESS)
					{
						return $this->_redirectMessage('导入成功', '返回销售单浏览页面', url('Sales::Order/List', array('shop_id' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
					}
					else
					{
						return $this->_redirectMessage('导入部分失败', $sales_order_result['message'], url('Sales::Order/List', array('shop_id' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $sales_order_result['ack']);
					}
				}
				else
				{
					return $this->_redirectMessage('上传文件失败', $upload_result['message'], $_SERVER['HTTP_REFERER'], $upload_result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('导入失败', '请选择店铺', url('Sales::Order/Import'), FAILURE);
		}
	}
	
	function actionImportWishOrderByAPI()
	{
		$this->_view['title'] = '导入wish订单（API）';
		if ( ! empty($_POST['shop_id']) && ( ! empty($_POST['begin_sales_time'])))
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::getWishOrderByAPI($_POST['shop_id'], $_POST['begin_sales_time']);
				if ($result['ack'] == SUCCESS)
				{
					$order = $result['data'];
					$orders = array();
					foreach ($order as $o)
					{
						if ($o['Order']['state'] == "APPROVED")
						{
							$country = Country::find('code=?', $o['Order']['ShippingDetail']['country'])->asArray()->getOne();
							$country_name_en = $country ? $country['en_name'] : '';
							$country_name_cn = $country ? $country['cn_name'] : '';
							$currency_db = Currency::find('code=?', 'USD')->asArray()->getOne();
							$shipping_method = ($country['code'] == 'US') ? 'GZ_N_BY_IEUB' : 'GZ_N_SG_Package';
							$new = array();
							$new['shop_id'] = $_POST['shop_id'];
							$new['shop_order_number'] = $o['Order']['order_id'];
							$new['paid_time'] = date('Y-m-d H:i:s', strtotime($o['Order']['order_time']));
							$new['sales_time'] = date('Y-m-d H:i:s', strtotime($o['Order']['order_time']));
							$new['shop_buyer_id'] = $o['Order']['ShippingDetail']['name'];
							$new['fullname'] = $o['Order']['ShippingDetail']['name'];
							$new['phone'] = isset($o['Order']['ShippingDetail']['phone_number']) ? $o['Order']['ShippingDetail']['phone_number'] : 0;
							$new['email'] = '';
							$new['street1'] = $o['Order']['ShippingDetail']['street_address1'];
							$new['street2'] = isset($o['Order']['ShippingDetail']['street_address2']) ? $o['Order']['ShippingDetail']['street_address2'] : "";
							$new['city'] = $o['Order']['ShippingDetail']['city'];
							$new['state'] = isset($o['Order']['ShippingDetail']['state']) ? $o['Order']['ShippingDetail']['state'] : "";
							$new['zip'] = $o['Order']['ShippingDetail']['zipcode'];
							$new['country'] = $country_name_en;
							$new['country_cn'] = $country_name_cn;
							$new['currency_id'] = 2;
							$new['currency_rate'] = $currency_db['rate'];
							$new['shipping_fee'] = $o['Order']['shipping'] * $o['Order']['quantity'];
							$new['shipping_method'] = Shipping_Method::getShippingMethodByCode($shipping_method);
							$new['discount'] = 0;
							$new['amount'] = ($o['Order']['price'] + $o['Order']['shipping']) * $o['Order']['quantity'];
							$new['payment_method'] = Q::ini('custom_flag/sales_order_payment_method/paypal/value');
							$new['transaction_id'] = $o['Order']['transaction_id'];
							$item = array();
							$new_item = array();
							$new_item['shop_item_id'] = $o['Order']['product_id'];
							$new_item['shop_transaction_id'] = $o['Order']['transaction_id'];
							$new_item['product_basic_number'] = $o['Order']['sku'];
							$new_item['quantity'] = $o['Order']['quantity'];
							$new_item['sales_price'] = $o['Order']['price'];
							$item[] = $new_item;
							$new['item'] = $item;
							$orders[] = $new;
						}
					}
					$result = Sales_Order::import($orders);
					if($result['ack'] == SUCCESS)
					{
						return $this->_redirectMessage('导入成功', '返回销售单浏览页面', url('Sales::Order/List', array('shop_id' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $result['ack']);
					}
					else
					{
						return $this->_redirectMessage('导入部分失败', $result['message'], url('Sales::Order/List', array('shop_id' => $_POST['shop_id'], 'order_status' => array(Q::ini('custom_flag/sales_order_handle_status/new/value') => Q::ini('custom_flag/sales_order_handle_status/new/value')), 'is_search' => 1)), $result['ack']);
					}
				}
			}
			else
			{
				return $this->_redirectMessage('导入失败', $mapping['message'], url('Sales::Order/Import'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('导入失败', '请选择店铺/日期', url('Sales::Order/Import'), FAILURE);
		}
	}
	
	function actionRefund()
	{
		$this->_view['title'] = '新建退款单';
		if ($this->_context->isPOST())
		{
			$sales_order = Sales_Order::find('id=?', $_POST['id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				if (empty($_POST['refund_method']))
				{
					return $this->_redirectMessage('退款方式不能为空！', '正在返回..', $_SERVER['HTTP_REFERER'], FAILURE);
				}
				$result = Sales_Refund::create($_POST['id'], $_POST);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('退款成功', '正在返回..', url('Sales::Order/List'), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('退款失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('退款失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
	}
	
	function actionRefundList()
	{
		$this->_view['title'] = '退款单列表';
		$shop = Shop_User_Mapping::getTreeShopByPlatform();
		$this->_view['shop'] = $shop;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['shop_user_mapping'] = Shop_User_Mapping::getShopIdByUserId();
		$result = Sales_Refund::Search($condition, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$sales_refund = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Sales::Order/RefundList', $condition));
			$this->_view['page'] = $page->getPage();
			$this->_view['sales_refund'] = $sales_refund;
		}
	}
	
	function actionRefundEdit()
	{
		$this->_view['title'] = '退款单编辑';
		$id = isset($_GET['id']) ? $_GET['id'] : '';
		if ($id)
		{
			$sales_refund = Sales_Refund::find('sales_refund.id=?', $id)
				->joinLeft('sales_order', 'shop_id', 'sales_order.id=sales_refund.sales_order_id')
				->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_refund['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$this->_view['sales_refund'] = $sales_refund;
			}
			else
			{
				echo $mapping['message'] . ', 请刷新页面！';exit;
			}
		}
	}
	
	function actionRefundEditSave()
	{
		$this->_view['title'] = '退款单编辑保存';
		if ($_POST['id'])
		{
			$sales_refund = Sales_Refund::find('sales_refund.id=?', $_POST['id'])
				->joinLeft('sales_order', 'shop_id', 'sales_order.id=sales_refund.sales_order_id')
				->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_refund['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$sales_refund = array(
					'id' => $_POST['id'],
					'type' => $_POST['type'],
					'refund_amount' => $_POST['refund_amount'],		
					'refund_account' => $_POST['refund_account'],
					'receive_transaction_id' => trim($_POST['receive_transaction_id']),
					'refund_method' => $_POST['refund_method'],
					'categories_name' => trim($_POST['categories_name']),
					'reason' => isset($_POST['reason']) ? $_POST['reason'] : '',
					'notes' => trim($_POST['notes'])
				);
				$result = Sales_Refund::edit($sales_refund);
				if ($result['ack'] == SUCCESS)
				{
					echo '保存成功';exit;
				}
				else
				{
					echo $result['message'];exit;
				}
			}
			else
			{
				echo $mapping['message'];exit;
			}
		}
	}
	
	function actionRefundDelete()
	{
		$this->_view['title'] = '退款单删除';
		$sales_refund = Sales_Refund::find('sales_refund.id=?', $_GET['id'])
			->joinLeft('sales_order', 'shop_id', 'sales_order.id=sales_refund.sales_order_id')
			->asArray()->getOne();
		$mapping = Shop_User_Mapping::checkMapping($sales_refund['shop_id']);
		if ($mapping['ack'] == SUCCESS)
		{
			$result = Sales_refund::delete($_GET['id']);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('删除成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('删除失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('删除失败', $mapping['message'], url('Sales::Order/RefundList'), $result['ack']);
		}
	}
	
	function actionRefundAudit()
	{
		$this->_view['title'] = '退款单审核';
		if ($this->_context->isPOST())
		{
			$refund = array();
			$ids = explode(',', $_POST['id']);
			$sales_refund = Sales_Refund::find('sales_refund.id in (?)', $ids)
				->joinLeft('sales_order', 'shop_id', 'sales_order.id=sales_refund.sales_order_id')
				->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_refund, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$refund['refund_transaction_id'] = isset($_POST['refund_transaction_id']) ? trim($_POST['refund_transaction_id']) : '';
				$refund['refund_time'] = isset($_POST['refund_time']) ? $_POST['refund_time'] : CURRENT_DATETIME;
				$result = Sales_Refund::auditRefundFinance($ids, $refund);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('退款成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('退款失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('退款失败', $mapping['message'], url('Sales::Order/RefundList'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirect(url('Sales::Order/RefundList'));
		}
	}
	
	function actionRefundInfo()
	{
		$this->_view['title'] = '退款详细信息';
		if ($_GET['id'])
		{
			$refund = Sales_Refund::find('id=?', $_GET['id'])->asArray()->getOne();
			$sales_order_id = $refund['sales_order_id'];
			$sales_order = Sales_Order::find('sales_order.id=?', $sales_order_id)
				->joinLeft('shop', 'shop.name as shop_name', 'shop.id=sales_order.shop_id')
				->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$refund['item'] = Sales_Refund::find('sales_order_id=?', $sales_order_id)
					->joinLeft('sales_order', '', 'sales_refund.sales_order_id=sales_order.id')
					->joinLeft('currency', 'currency.symbol, currency.code', 'currency.id=sales_order.currency_id')
					->asArray()->getAll();
				$this->_view['sales_order'] = $sales_order;
				$this->_view['refund'] = $refund['item'];
			}
			else
			{
				echo $mapping['message'] . ', 请刷新页面！';exit;
			}
		}
	}
	
	function actionRefundBulkEdit()
	{
		$this->_view['title'] = '退款信息批量修改';
		if ($this->_context->isPOST())
		{
			$sales_refund = array();
			foreach ($_POST as $key => $val)
			{
				$refund_info = Q::normalize($val, "\n");
				foreach ($refund_info as $ri)
				{
					$tmp = Q::normalize($ri, ',');
					$sales_refund[] = $tmp[0];
				}
			}
			if ($sales_refund)
			{
				$sales_refund = Sales_Refund::find('sales_refund.id in (?)', array_unique($sales_refund))
					->joinLeft('sales_order', 'shop_id', 'sales_order.id=sales_refund.sales_order_id')
					->asArray()->getAll();
				$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_refund, 'shop_id');
				$mapping = Shop_User_Mapping::checkMapping($shop_id);
				if ($mapping['ack'] == SUCCESS)
				{
					$result = Sales_Refund::editSalesRefundInfo($_POST);
					if ($result['ack'] == SUCCESS)
					{
						$this->_view['success'] = '操作成功！';
					}
					else
					{
						$this->_view['message'] = $result['message'];
					}
				}
				else
				{
					$this->_view['failure'] = $mapping['message'] . ', 请刷新页面！';
				}
			}
		}
	}
	
	function actionReturnCreate()
	{
		$this->_view['title'] = '创建退货单';
		if (isset($_GET['id']) && $_GET['id'])
		{
			$get_id = $_GET['id'];
		}
		if (isset($_GET['is_search']) && $_GET['is_search'] == 1)
		{
			if ( ! empty($_GET['number']))
			{
				$columns = array(
					'sales_order.id, sales_order.number, sales_order.tracking_number',
					'shop.name as shop_name',
					'user.name as sales_user_name',
					'sales_order.sales_time',
					'sales_order.handle_status'
				);
				$sales_order_result = Sales_Order::find('number=? or tracking_number=?', $_GET['number'], $_GET['number'])
					->joinLeft('shop', '', 'shop.id = sales_order.shop_id')
					->joinLeft('user', '', 'user.id = sales_order.sales_user_id')
					->setColumns($columns)->asArray()->getAll();
				if (count($sales_order_result) == 1)
				{
					if ($sales_order_result[0]['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/shipped/value'))
					{
						$get_id = $sales_order_result[0]['id'];
					}
					else
					{
						$this->_view['report'] = $sales_order_result;
					}
				}
				elseif (count($sales_order_result) > 1)
				{
					$this->_view['report'] = $sales_order_result;
				}
			}
		}
		if (isset($get_id) && $get_id)
		{
			$sales_order = Sales_Order::find('id=?', $get_id)->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$this->_view['sales_order'] = $sales_order;
				$sales_order_item = Sales_Order_Item::find('sales_order_id=?', $get_id)
					->joinLeft('product_basic', 'name, number', 'product_basic.id=sales_order_item.product_basic_id')
					->asArray()->getAll();
				$this->_view['sales_order_item'] = $sales_order_item;
			}
			else
			{
				return $this->_redirectMessage('操作失败', $mapping['message'], url('Sales::Order/List'), $mapping['ack']);
			}
		}
	}
	
	function actionReturnCreateSave()
	{
		$this->_view['title'] = '创建退货单（保存）';
		if ($this->_context->isPOST())
		{
			$sales_order = Sales_Order::find('number=?', $_POST['number'])->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$key_arr = array();
				$item_arr = array();
				foreach ($_POST as $key => $value)
				{
					if (substr($key,0,8) == 'quantity')
					{
						$key_arr[] = substr($key,8,strlen($key)-8);
					}
				}
				foreach ($key_arr as $k)
				{
					$temp = array();
					if (isset($_POST['check'.$k]))
					{
						$temp['sales_order_item_id'] = $k;
						$temp['product_basic_id'] = $_POST['product_basic_id'.$k];
						$temp['quantity'] = $_POST['quantity'.$k]; 
						$item_arr[$k] = $temp;
					}
				}
				$return = $_POST;
				$return['item'] = $item_arr;
				$result = Sales_Return::create($sales_order['id'], $return);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('保存成功！', '已成功保存销售退货信息.', url('Sales::Order/ReturnCreate'), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('保存失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('创建失败', $mapping['message'], url('Sales::Order/ReturnCreate'), $mapping['ack']);
			}
		}
	}
	
	function actionReturnEdit()
	{
		$this->_view['title'] = '编辑退货单';
		$id = isset($_GET['id']) ? $_GET['id'] : 0;
		if ($id)
		{
			$return = Sales_Return::find('sales_return.id=?', $id)
				->joinLeft('shop', 'shop.name as shop_name', 'shop.id=sales_return.shop_id')
				->joinLeft('sales_order', 'sales_order.number as sales_order_number', 'sales_order.id=sales_return.sales_order_id')
				->joinLeft('currency', 'symbol as sales_symbol', 'sales_order.currency_id=currency.id')
				->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($return['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$this->_view['sales_return'] = $return;
				$return_item = Sales_return_item::find('sales_return_id=?', $return['id'])->asArray()->getAll();
				$sales_order_item = Sales_Order_Item::find('sales_order_id=?', $return['sales_order_id'])->asArray()->getAll();
				foreach ($sales_order_item as &$soi)
				{
					$soi['has_return'] = false;
					$soi['return_quantity'] = 0;
					foreach ($return_item as $ri)
					{
						if ($soi['product_basic_id'] == $ri['product_basic_id'])
						{
							$soi['has_return'] = true;
							$soi['return_quantity'] = $ri['quantity'];
							break;
						}
					}
				}
				unset($soi);
				$this->_view['sales_order_item'] = $sales_order_item;
			}
			else
			{
				return $this->_redirectMessage('操作失败', $mapping['message'], url('Sales::Order/ReturnList'), $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('错误', '该销售退货单不存在', url('Sales::Order/ReturnList'), FAILURE);
		}
	}
	
	function actionReturnEditSave()
	{
		$this->_view['title'] = '编辑退货单（保存）';
		$product_info = array_chunk(json_decode($_POST['product_info']), 3);
		if ($this->_context->isPOST())
		{
			$sales_return = Sales_Return::find('id=?', $_POST['sales_return_id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_return['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$item_arr = array();
				foreach ($product_info as $p)
				{
					$temp = array();
					$temp['product_basic_id'] = $p[0];
					$temp['sales_order_item_id'] = $p[1];
					$temp['quantity'] = $p[2];
					$item_arr[$p[1]] =$temp;
				}
				$sales_return = array(
					'id' => $_POST['sales_return_id'],
					'reason' => $_POST['reason'],
					'item' => $item_arr
				);
				$result= Sales_Return::edit($sales_return);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('保存成功', '正在返回..', url('Sales::order/ReturnList'), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('保存失败', $result['message'], $_POST['history'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('保存失败', $mapping['message'], url('Sales::order/ReturnList'), $mapping['ack']);
			}
		}
	}
	
	function actionReturnList()
	{
		$this->_view['title'] = '退货单列表';
		$shop = Shop_User_Mapping::getTreeShopByPlatform();
		$this->_view['shop'] = $shop;
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['shop_user_mapping'] = Shop_User_Mapping::getShopIdByUserId();
		$result = Sales_Return::Search($condition, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$sales_return = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Sales::Order/ReturnList', $condition));
			$this->_view['page'] = $page->getPage();
			Sales_Order_Notes::getOrderNotes($sales_return);
			$this->_view['sales_return'] = $sales_return;
		}
	}
	
	function actionReturnInfo()
	{
		$this->_view['title'] = '退货详细信息';
		if ($_GET['id'])
		{
			$return = Sales_Return::find('id=?', $_GET['id'])->asArray()->getOne();
			$sales_order_id = $return['sales_order_id'];
			$sales_order = Sales_Order::find('sales_order.id=?', $sales_order_id)
				->joinLeft('shop', 'shop.name as shop_name', 'shop.id=sales_order.shop_id')
				->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_order['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$return['item'] = Sales_return_item::find('sales_return_id=?', $return['id'])
					->joinLeft('product_basic', 'number as product_number, name as product_name', 'product_basic.id=sales_return_item.product_basic_id')
					->joinLeft('sales_order_item', 'quantity as sales_quantity', 'sales_order_item.id=sales_return_item.sales_order_item_id')
					->asArray()->getAll();
				$this->_view['sales_return'] = $return;
				$this->_view['sales_order'] = $sales_order;
				$this->_view['return'] = $return['item'];
			}
			else
			{
				echo $mapping['message'] . ', 请刷新页面！';exit;
			}
		}
	}
	
	function actionReturnDelete()
	{
		$this->_view['title'] = '销售退货单删除';
		if ($_GET['id'])
		{
			$sales_return = Sales_Return::find('id=?', $_GET['id'])->asArray()->getOne();
			$mapping = Shop_User_Mapping::checkMapping($sales_return['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Return::delete($_GET['id']);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('删除成功', '返回列表', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('删除失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('删除失败', $mapping['message'], url('Sales::order/ReturnList'), $mapping['ack']);
			}
		}
	}
	
	function actionOutList()
	{
		$this->_view['title'] = '出库单列表';
		$this->_view['shop_group'] = Shop_User_Mapping::getTreeShopByPlatform();
		$this->_view['shipping_method'] = Shipping_Method::getTreeShippingMethod();
		if (isset($_GET['is_search']) && $_GET['is_search'] == 1)
		{
			$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
			$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
			$condition = Helper_BSS_Normal::buildCondition();
			$condition['trash_status'] = Q::ini('custom_flag/sales_order_trash_status/normal/value');
// 			$condition['is_tracking'] = flase;
			$condition['shop_user_mapping'] = Shop_User_Mapping::getShopIdByUserId();
			$result = Sales_Order::search($condition, $cp, $ps);
			if ($result['ack'] == SUCCESS)
			{
				$order = $result['data'];
				$page = new Helper_BSS_Page($result['pagination'], url('Sales::Order/OutList', $condition));
				$this->_view['page'] = $page->getPage();
				$this->_view['order'] = $order;
			}
		}
	}
	
	function actionExpressNumber()
	{
		$this->_view['title'] = '更新物流号';
		$id = $_REQUEST['id'];
		$lsp_number = trim($_REQUEST['number']);
		QDB::getConn()->execute('update sales_order set lsp_number=\'' . $lsp_number . '\' where sales_order_id=' . $id);
		echo 1;exit;
	}
	
	function actionTrackingNumber()
	{
		$this->_view['title'] = '更新追踪号';
		$id = $_REQUEST['id'];
		$tracking_number = trim($_REQUEST['number']);
		QDB::getConn()->execute('update sales_order set tracking_number=\'' . $tracking_number .'\' where id='.$id);
		echo 1;exit;
	}
	
	function actionUpdateSynFlag()
	{
		$this->_view['title'] = '更新物流同步标识';
		$id = $_REQUEST['id'];
		$flag = $_REQUEST['syn_flag'];
		QDB::getConn()->execute('update sales_order set synchronous_flag=\'' . $flag .'\' where id='.$id);
		echo 1;exit;
	}
	
	function actionMarkShipped()
	{
		$this->_view['title'] = '标记后台发货';
		if ($this->_context->isPOST() && isset($_GET['type']))
		{
			$ids = explode(',', $_POST['ids']);
			$sales_order = Sales_Order::find('id in (?)', $ids)->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = ($_GET['type'] == 'Zencart') ? Sales_Order::zencartOrderMarkShipped($ids) : (($_GET['type'] == 'Ebay') ? Sales_Order::ebayOrderMarkShipped($ids) : Sales_Order::amazonOrderMarkShipped($ids, $_GET['type']));
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('同步成功', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('同步失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('同步失败', $mapping['message'], url('Sales::Order/OutList'), $mapping['ack']);
			}
		}
	}
	
	function actionPushTracking()
	{
		$this->_view['title'] = '推送追踪号';
		if ($_POST['ids'])
		{
			$ids = explode(',', $_POST['ids']);
			$sales_order = Sales_Order::find('id in (?)', $ids)->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$result = Sales_Order::pushTracking($ids);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('推送成功', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('推送失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('推送失败', $mapping['message'], url('Sales::Order/OutList'), $mapping['ack']);
			}
		}
	}
	
	function actionExportShipmentFile()
	{
		$this->_view['title'] = '导出追踪号文件';
		if ($_GET['type'] == 'amazon')
		{
			$ids = explode(',', $_POST['ids']);
			$sales_order = Sales_Order::find('id in (?)', $ids)->asArray()->getAll();
			$shop_id = Helper_BSS_Array::getDistinctValueToArrayByKey($sales_order, 'shop_id');
			$mapping = Shop_User_Mapping::checkMapping($shop_id);
			if ($mapping['ack'] == SUCCESS)
			{
				$text = Sales_Order::exportShipmentFileAmazon($ids);
				header( "Content-type:   application/octet-stream ");
				header("Content-Type: application/download");
				Header( "Accept-Ranges:   bytes ");
				header( "Content-Disposition:   attachment;   filename=AmazonShipment-".date('m.d').".txt ");
				header( "Cache-Control:   must-revalidate,   post-check=0,   pre-check=0 ");
				header( "Pragma:   public ");
				echo $text;
			}
			else
			{
				return $this->_redirectMessage('导出追踪号文件失败', $mapping['message'], url('Sales::Order/OutList'), $mapping['ack']);
			}
		}
		exit;
	}
	
	function actionChangeShippingMethod()
	{
		$this->_view['title'] = '批量修改订单邮寄方式';
		if ($this->_context->isPOST() && $_POST['id'] && $_POST['shipping_method_id'])
		{
			$change_flag = 1;
			$shipping_method_warehouse = Shipping_Method::find('id=?', $_POST['shipping_method_id'])->asArray()->getOne();
			$id = explode(',', $_POST['id']);
			$sales_order = Sales_Order::find('id in (?)', $id)->asArray()->getAll();
			foreach ($sales_order as $so)
			{
				if ( ! ($so['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/checkout/value') || ($so['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/new/value') || $so['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/sales_hold/value')) && $so['warehouse_id'] == $shipping_method_warehouse['warehouse_id']))
				{
					$change_flag = 0;
				}
			}
			if ($change_flag == 1)
			{
				QDB::getConn()->execute('update sales_order set lsp_number=null, tracking_number=null, synchronous_flag=null, shipping_method = \'' . $_POST['shipping_method_id'] . '\' where id in (' . $_POST['id'] . ')');
				return $this->_redirectMessage('批量修改订单邮寄方式成功', '正在返回...', $_SERVER['HTTP_REFERER'], SUCCESS);
			}
			return $this->_redirectMessage('批量修改订单邮寄方式失败', '所选择订单的订单状态不是新单/销售确认或所选择订单的仓库和所选择邮寄方式仓库不一致', $_SERVER['HTTP_REFERER'], FAILURE);
		}
		return $this->_redirectMessage('批量修改订单邮寄方式失败', '请选择邮寄方式', $_SERVER['HTTP_REFERER'], FAILURE);
	}
	
	function actionPrintSpecial()
	{
		$this->_view['title'] = '特殊打印';
	}
	
	function actionPrintSpecialAddress()
	{
		$this->_view['title'] = '特殊打印地址单';
		$order = Sales_Order::find('number=? or tracking_number=?', $_GET['number'], $_GET['number'])->asArray()->getAll();
		if (count($order))
		{
			if (count($order) == 1)
			{
				$order = $order[0];
				$shipping_method = Shipping_Method::find('id=?', $order['shipping_method'])->asArray()->getOne();
				$result = OLM_Address::$shipping_method['address_model']($order['id']);
				if ($result['ack'] == SUCCESS)
				{
					header('Content-Type: application/pdf');
					header('Cache-Control: private, must-revalidate, post-check=0, max-age=1');
					header('Pragma: public');
					echo $result['label'];
					exit;
				}
				else
				{
					echo $order['number'] . $result['message'];
				}
			}
			else
			{
				echo '有多张订单';
			}
		}
		else
		{
			echo '没有符合的地址单';
		}
	}
}
